﻿/************************************************************************
* Copyright (c) 2018 All Rights Reserved.
*命名空间：AOP.Filter.Jurisdiction
*文件名： JurisdictionFilterAttribute
*创建人： kingling
*创建时间：2018/7/5 12:22:29
*描述
*=======================================================================
*修改标记
*修改时间：2018/7/5 12:22:29
*修改人：kingling
*描述：
************************************************************************/

using CacheService.Standard;
using Common.Standard;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using MODEL.Model;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;

namespace AOP.Filter.Jurisdiction
{
    /// <summary>
    /// 放在登录之后
    /// </summary>
    public class JurisdictionFilterAttribute : IActionFilter
    {
        ICache cache;
        public JurisdictionFilterAttribute(ICache cache)
        {
            this.cache = cache;
        }
        public void OnActionExecuted(ActionExecutedContext context)
        {
            //throw new NotImplementedException();
        }

        public void OnActionExecuting(ActionExecutingContext context)
        {
            var actiondescriptor = context.ActionDescriptor as ControllerActionDescriptor;
            //控制器上是否有过滤标签
            var no_Jurisdiction_controller = context.Controller.GetType().IsDefined(typeof(NoJurisdictionAttribute), true);
            if (no_Jurisdiction_controller)
            {
                return;
            }
            //控制器上是否有过滤标签
            var no_Jurisdiction_action = actiondescriptor.MethodInfo.IsDefined(typeof(NoJurisdictionAttribute), true);
            if (no_Jurisdiction_action)
            {
                return;
            }
            //获取权限名
            var names = actiondescriptor.MethodInfo.GetCustomAttributes(typeof(DescriptionAttribute), true);
            var power = names.Length > 0 ? ((DescriptionAttribute)names[0]).Description : $"{actiondescriptor.ControllerName.Replace("Controller", "")}/{actiondescriptor.ActionName}";

            var key = context.HttpContext.Request.Cookies["key"];
            var user = cache.get<SystemManager>(key);
            if (user.SystemRule.SystemJurisdictions.Where(x => x.name == power).Count() == 0)
            {
                if (actiondescriptor.MethodInfo.ReturnType.Name == "IActionResult")
                {
                    context.Result = new RedirectResult("/error/ban");
                    return;
                }
                else {
                    throw new Error("权限不足");
                }
            }
        }
    }
}
